# 该脚本用来实现BurpSuite的Repeater功能
"""
使用说明:
1, 在浏览器的通过Node.jsfetch的方式拷贝报文
2, 将拷贝的内容粘贴到同目录的fetch.js文件中
3, 直接运行repeater.py, 用于重新发送该报文
4, 直接运行bp_helper.py, 用于打印bp格式的请求内容, 将打印的内容拷贝至bp工具后操作即可.
   注意: 拷贝到bp工具后, 需要设置host
"""
import re
import sys
from fetch_parser import Parser

try:
    import requests
except ModuleNotFoundError:
    print("Package requests is required.")
    sys.exit()


"""
功能: 格式化打印键值对
参数: 
    data(dict): 待打印的数据
    ident(str): 缩进
"""
def print_kv(data, ident=""):
    for key in data:
        print("%s%s: %s" % (ident, key, data.get(key)))


class Repeater:
    """
    重放类, 对fetch中的内容进行
    """
    def __init__(self):
        self.p = Parser()

    def run(self, file=""):
        p = self.p
        p.parse_file(file)

        print("request:")
        print("\turl: \n\t\t%s %s" % (p.method, p.url))
        print("\theaders:")
        print_kv(p.headers, "\t\t")

        if p.method == "GET":
            r = requests.get(p.url, headers=p.headers, verify=False)
        elif p.method == "POST":
            if "application/json" in p.headers["content-type"]:
                if p.body.startswith("{") and p.body.endswith("}"):
                    p.body = p.body.replace("true", "True")
                    p.body = eval(p.body)
                    r = requests.post(p.url, headers=p.headers, json=p.body, verify=False)
                elif "&" in p.body and "=" in p.body:
                    r = requests.post(p.url, headers=p.headers, data=p.body, verify=False)
            elif "application/x-www-form-urlencoded" in p.headers.get("content-type"):
                r = requests.post(p.url, headers=p.headers, data=p.body, verify=False)
            else:
                print(f"Invalid content-type:{p.method}")
                sys.exit()
        else:
            print(f"Invalid method:{p.method}")
            sys.exit()

        print("response:")
        print("\tcode:\n\t\t", r.status_code)
        print("\theaders:")
        print_kv(r.headers, "\t\t")

        if r.headers.get("content-disposition"):  # 返回为文件的情况
            output = re.findall(re.compile('filename="(.*)"'), r.headers.get("content-disposition"))[0]
            with open(output, "wb") as f:
                f.write(r.content)
            print(f"Save to {output} successful!")
        elif "utf-8" in r.headers.get("content-type").lower():
            print("\tbody: \n\t\t", r.content.decode("utf-8"))


if __name__ == "__main__":
    rep = Repeater()
    rep.run()
